package com.app.util;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import ch.ethz.ssh2.Connection;
import ch.ethz.ssh2.Session;
import ch.ethz.ssh2.StreamGobbler;

public class SSHUtil {
	public static void main(String[] args){
		/*System.out.println("start：" + DBUtil.getCurrentDateTime());
		SSHUtil ssh = new SSHUtil();
		ssh.connect("172.16.73.130",22,"root","1qaz2wsx");
		String c2 = ssh.execCommand("unzip /data/zsl/real_his5.zip -d /data/zsl");
		System.out.println(c2);
		ssh.disconnect();
		System.out.println("任务结束：" + DBUtil.getCurrentDateTime());*/
		
	}
	
	private static Log log = LogFactory.getLog(SSHUtil.class);
	private Connection conn;
	private Session sess;
	private BufferedReader reader;
	public boolean connect(String host,String username,String password){
		return this.connect(host, 22, username, password);
	}
	public boolean connect(String host,int port, String username, String password) {
		boolean isAuthenticated = false;
		try {
			conn = new Connection(host,port);
			conn.connect();
			isAuthenticated = conn.authenticateWithPassword(username,password);
			if (isAuthenticated == false)
				throw new IOException("Authentication failed.");
		} catch (Exception e) {
			log.error(e.getMessage());
		}
		return isAuthenticated;
	}
	public String execCommand(String command){
		try {
			sess = conn.openSession();
			sess.execCommand(command);
			reader = new BufferedReader(new InputStreamReader(new StreamGobbler(sess.getStdout())));
			StringBuffer sb = new StringBuffer();
			String t;
			while((t = reader.readLine()) != null){
				sb.append(t);
			}
			return sb.toString();
		} catch(Exception e){
			log.error(e.getMessage());
		}finally{
			sess.close();
		}
		return null;
	}
	public void disconnect() {
		try {
			conn.close();
		}catch(Exception e){
		}
	}
}
